/**
 * router/index.ts
 *
 * Automatic routes for `./src/pages/*.vue`
 */

// Composables
import {
  createRouter,
  createWebHistory,
} from "vue-router";
// 由于找不到模块“virtual:generated-layouts”，暂时注释掉该导入
import { setupLayouts } from "virtual:generated-layouts";
import { BASE_URL } from "../env";
import { useAuthStore } from "../stores/auth";
// import { routes } from 'vue-router/auto-routes'

const routes = [
  {
    path: "/login",
    name: "Login",
    component: () => import("../pages/LoginPage.vue"),
  },
  // {
  //   path: "/diag-list",
  //   name: "DiagList",
  //   component: () => import("../pages/DiagList.vue"),
  //   meta: {
  //     requiresAuth: true
  //   }
  // },
  // {
  //   path: "/user-info",
  //   name: "UserInfo",
  //   component: () => import("../pages/UserInfo.vue"),
  //   meta: {
  //     requiresAuth: true
  //   }
  // },
  // {
  //   path: "/record-detail/:id",
  //   name: "RecordDetail",
  //   component: () => import("../pages/RecordDetail.vue"),
  //   meta: {
  //     requiresAuth: true
  //   }
  // },
  // {
  //   path: "/feedback/:id",
  //   name: "RecordFeedback",
  //   component: () => import("../pages/RecordFeedback.vue"),
  //   meta: {
  //     requiresAuth: true
  //   }
  // },
  {
    path: "/questionnaire/:id",
    name: "QuestPage",
    component: () => import("../pages/QuestPage.vue"),
    meta: {
      requiresAuth: true
    }
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("../pages/NotFound.vue"),
    meta: {
      requiresAuth: true
    }
  },
];

const router = createRouter({
  history: createWebHistory(BASE_URL),
  routes: setupLayouts(routes),
});

// Workaround for https://github.com/vitejs/vite/issues/11804
router.onError((err, to) => {
  if (err?.message?.includes?.("Failed to fetch dynamically imported module")) {
    if (!localStorage.getItem("vuetify:dynamic-reload")) {
      console.log("Reloading page to fix dynamic import error");
      localStorage.setItem("vuetify:dynamic-reload", "true");
      location.assign(to.fullPath);
    } else {
      console.error("Dynamic import error, reloading page did not fix it", err);
    }
  } else {
    console.error(err);
  }
});

router.isReady().then(() => {
  localStorage.removeItem("vuetify:dynamic-reload");
});

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  authStore.initAuth()

  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    console.log(authStore.isLoggedIn);
    next({
      name: 'Login' as any,
      query: { redirect: to.fullPath},
    })
  } else {
    next()
  }
});

export default router;
